/*
 * This file is part of TradeHelper library.
 *
 * TradeHelper library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TradeHelper library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TradeHelper library.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rag.forum.ui;

import com.alee.laf.list.DefaultListModel;
import com.alee.laf.scroll.WebScrollPane;
import com.alee.laf.text.WebTextField;
import com.alee.managers.hotkey.Hotkey;
import com.alee.managers.popup.PopupManager;
import com.alee.managers.popup.WebPopup;
import com.alee.utils.SwingUtils;
import com.alee.utils.swing.Timer;
import com.rag.core.Item;
import com.rag.utils.RagUtils;

import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

/**
 * User: mgarin Date: 18.04.12 Time: 12:19
 */

public class ItemField extends WebTextField
{
    private List<ItemListener> listeners = new ArrayList<ItemListener> ();

    private WebPopup listPopup;
    private DefaultListModel itemListModel;
    private ItemList itemList;
    private WebScrollPane listScroll;

    public ItemField ()
    {
        super ( 15 );
        setDrawFocus ( false );

        listPopup = new WebPopup ();
        listPopup.setCloseOnFocusLoss ( false );
        listPopup.setBackgroundPainter ( null );

        itemListModel = new DefaultListModel ();
        itemList = new ItemList ( itemListModel );
        itemList.setOpaque ( true );
        //DataTipManager.get ().register ( itemList );

        listScroll = new WebScrollPane ( itemList );
        listScroll.setDrawFocus ( false );
        listPopup.add ( listScroll );

        addFocusListener ( new FocusAdapter ()
        {
            public void focusLost ( FocusEvent e )
            {
                listPopup.hidePopup ();
                ItemField.this.clear ();
            }
        } );
        addKeyListener ( new KeyAdapter ()
        {
            public void keyPressed ( KeyEvent e )
            {
                if ( Hotkey.ENTER.isHotkeyTriggered ( e ) )
                {
                    if ( listPopup.isShowing () && itemList.getSelectedIndex () != -1 )
                    {
                        listPopup.hidePopup ();
                        fireItemSelected ( ( Item ) itemList.getSelectedValue () );
                    }
                }
                else if ( Hotkey.HOME.isHotkeyTriggered ( e ) )
                {
                    if ( listPopup.isShowing () && itemList.getModelSize () > 0 )
                    {
                        itemList.setSelectedIndex ( 0 );
                        e.consume ();
                    }
                }
                else if ( Hotkey.UP.isHotkeyTriggered ( e ) )
                {
                    if ( listPopup.isShowing () && itemList.getSelectedIndex () > 0 )
                    {
                        itemList.setSelectedIndex ( itemList.getSelectedIndex () - 1 );
                        e.consume ();
                    }
                }
                else if ( Hotkey.DOWN.isHotkeyTriggered ( e ) )
                {
                    if ( listPopup.isShowing () &&
                            itemList.getSelectedIndex () < itemList.getModelSize () - 1 )
                    {
                        itemList.setSelectedIndex ( itemList.getSelectedIndex () + 1 );
                        e.consume ();
                    }
                }
                else if ( Hotkey.END.isHotkeyTriggered ( e ) )
                {
                    if ( listPopup.isShowing () && itemList.getModelSize () > 0 )
                    {
                        itemList.setSelectedIndex ( itemList.getModelSize () - 1 );
                        e.consume ();
                    }
                }
                else if ( Hotkey.ESCAPE.isHotkeyTriggered ( e ) )
                {
                    ItemField.this.clear ();
                }
            }
        } );
        itemList.addMouseMotionListener ( new MouseMotionAdapter ()
        {
            public void mouseMoved ( MouseEvent e )
            {
                itemList.setSelectedIndex ( itemList.locationToIndex ( e.getPoint () ) );
            }
        } );
        itemList.addMouseListener ( new MouseAdapter ()
        {
            public void mousePressed ( MouseEvent e )
            {
                if ( itemList.getSelectedIndex () != -1 )
                {
                    listPopup.hidePopup ();
                    fireItemSelected ( ( Item ) itemList.getSelectedValue () );
                }
            }
        } );

        addCaretListener ( new CaretListener ()
        {
            private Timer delayTimer = null;

            public void caretUpdate ( CaretEvent e )
            {
                if ( delayTimer == null )
                {
                    delayTimer = new Timer ( 300 );
                    delayTimer.setRepeats ( false );
                    delayTimer.setUseEventDispatchThread ( false );
                    delayTimer.addActionListener ( new ActionListener ()
                    {
                        public void actionPerformed ( ActionEvent e )
                        {
                            updatePopup ();
                        }
                    } );
                }
                delayTimer.restart ();
            }
        } );
    }

    private String last = null;

    private void updatePopup ()
    {
        // Проверяем нужно ли показывать попап
        final String text = getText ().trim ();
        if ( last != null && last.equals ( text ) || text.equals ( "" ) )
        {
            if ( text.equals ( "" ) )
            {
                listPopup.hidePopup ();
                last = null;
            }
            return;
        }
        last = text;

        // Находим все совпадения с текстом
        final List<Item> items = RagUtils.findItems ( text );

        // Обновляем список
        SwingUtils.invokeLater ( new Runnable ()
        {
            public void run ()
            {
                if ( items.size () > 0 )
                {
                    // Обновляем содержимое списка
                    itemListModel.clear ();
                    itemListModel.addElements ( items );

                    // Обновляем кол-во видимых строк списка и выделение
                    itemList.setVisibleRowCount ( Math.min ( 15, items.size () ) );
                    itemList.setSelectedIndex ( 0 );

                    // Обновляем расположение попапа
                    Rectangle ifb = SwingUtils.getBoundsInWindow ( ItemField.this );
                    Dimension ps = listPopup.getPreferredSize ();
                    int fsw = ItemField.this.getShadeWidth ();
                    int lsw = listScroll.getShadeWidth ();
                    listPopup.setBounds ( ifb.x + fsw - lsw, ifb.y + ifb.height - fsw -
                            lsw + 1, ItemField.this.getWidth () - fsw * 2 + lsw * 2, ps.height );

                    // Обновляем видимость попапа
                    if ( !listPopup.isShowing () )
                    {
                        PopupManager.showPopup ( ItemField.this, listPopup, false );
                        ItemField.this.requestFocusInWindow ();
                    }
                    else
                    {
                        listPopup.revalidate ();
                    }
                }
                else if ( listPopup.isShowing () )
                {
                    listPopup.hidePopup ();
                }
            }
        } );
    }

    public void addItemListener ( ItemListener actionListener )
    {
        listeners.add ( actionListener );
    }

    public void removeItemListener ( ItemListener actionListener )
    {
        listeners.remove ( actionListener );
    }

    private void fireItemSelected ( Item item )
    {
        List<ItemListener> listenersCopy = new ArrayList<ItemListener> ();
        listenersCopy.addAll ( listeners );
        for ( ItemListener listener : listenersCopy )
        {
            listener.itemSelected ( item );
        }
    }
}